package com.mtw.bbs.common.core.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;


/**
 * 线程池配置
 */
@Configuration
public class AsyncConfiguration {

    @Bean("asyncExecutor")
    public ThreadPoolTaskExecutor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(getCorePoolSize());
        // 设置最大线程数
        executor.setMaxPoolSize(100);
        // 设置队列大小
        executor.setQueueCapacity(200);
        // 设置线程名前缀
        executor.setThreadNamePrefix("asyncExecutor-");
        //线程池维护线程所允许的空闲时间
        executor.setKeepAliveSeconds(30000);
        executor.setWaitForTasksToCompleteOnShutdown(true);

        executor.initialize();
        return executor;
    }


    @Bean("bizExecutor")
    public ThreadPoolTaskExecutor bizExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(getCorePoolSize());
        // 设置最大线程数
        executor.setMaxPoolSize(100);
        // 设置队列大小
        executor.setQueueCapacity(200);
        // 设置线程名前缀
        executor.setThreadNamePrefix("asyncExecutor-");
        //线程池维护线程所允许的空闲时间
        executor.setKeepAliveSeconds(30000);
        executor.setWaitForTasksToCompleteOnShutdown(true);

        executor.initialize();
        return executor;
    }


    @Bean(name = "schedulerExecutor")
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
        // 设置核心线程数
        executor.setPoolSize(10);
        // 设置线程名前缀
        executor.setThreadNamePrefix("schedulerExecutor-");
        //线程池维护线程所允许的空闲时间
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);

        executor.initialize();
        return executor;
    }


    /**
     * 计算核心线程数
     */
    private static Integer getCorePoolSize() {
        // cpu核心数 * 利用率 * （1 + （任务等待时间 / 任务计算时间））
        double result = Runtime.getRuntime().availableProcessors() * 0.8 * (1 + (1 / 1));
        return (int) result;
    }


}

